using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

using WindowsLive.Writer.Api;

namespace QuotesPlugin
{
    class Quotes4AllProvider : IQuotesProvider
    {
        public Quotes4AllProvider()
        {
            LoadFromCache();
        }
        public IQuotesEntry GetQuote(int index)
        {
            if (index < 0 || index >= this.QuotesCount)
                throw new ArgumentOutOfRangeException("index");

            return m_quotes[index];
        }
        public int QuotesCount
        {
            get { return m_quotes.Count; }
        }

        private void LoadFromCache()
        {
            // expiration is 15 minutes
            TimeSpan ts = DateTime.Now - m_cachedTime;
            if (ts >= new TimeSpan(0, 15, 0))
            {
                m_cachedTime = DateTime.Now;
                FeatchAll();                
            }
        }

        //TODO: change this to asyn style 
        private void FeatchAll()
        {
            PluginHttpRequest req = new PluginHttpRequest(this.requestUrl);
            Stream response = req.GetResponse(15 * 1000);
            IList<Quotes4AllEntry> entries =new Quotes4AllResponse(response).Parse();

            m_quotes.Clear();
            foreach (Quotes4AllEntry entry in entries)
            {
                m_quotes.Add(entry);
            }
        }

        private static List<IQuotesEntry> m_quotes = new List<IQuotesEntry>();
        private static DateTime m_cachedTime = DateTime.MinValue;

        //private List<Pair> settings = new List<Pair>();
        private string requestUrl 
            = "http://quotes4all.net/xml/quotes..xml?language=en&interval=1d&entries=10&encoding=UTF-8&imagesearchorder=author,%20default&dateformat=MM%2Fdd%2Fyyyy&timeformat=hh:mm%20a";

    }
}
